package com.huilian.tool.douyin.web.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.huilian.tool.common.utils.HuiLianHttpUtil;
import com.huilian.tool.douyin.enums.ScopeEnum;
import com.huilian.tool.douyin.web.service.DouYinService;
import com.huilian.tool.redis.ToolRedisKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.Serializable;
import java.util.Enumeration;
import java.util.concurrent.TimeUnit;

/**
 * @author 少凡
 * date 2022/5/27 11:58
 * version 1.0
 */


@Slf4j
@RequestMapping("/api/douyin")
@Controller
public class DouYinController {


    @Resource
    private DouYinService douYinService;
    @Autowired
    private RedisTemplate<String, Serializable> redisCacheTemplate;

    /**
     * 拼接获取授权的URL页面
     *
     * @return
     */
    @GetMapping("/getOauthCode")
    public String getOauthCode() {
        String redirectUri = "https://client.iotbox.cn/client/api/douyin/getOauthCode/redirect";
        String state = "state_example";
        String url = douYinService.getOauthCode(redirectUri, state);
        log.info("authUrl: " + url);
        return "redirect:" + url;
    }


    /**
     * 通过临时授权码获取用户accessToken
     *
     * @param request
     * @return
     */
    @GetMapping("/getOauthCode/redirect")
    @ResponseBody
    public String getOauthCodeRedirect(HttpServletRequest request) {
        String code = request.getParameter("code");
        String state = request.getParameter("state");
        System.out.println("code:" + code);
        System.out.println("state: " + state);
        JSONObject result = douYinService.getAccessToken(code);
        System.out.println(result);
        String errorCode = result.getString("error_code");
        if ("0".equals(errorCode)) {
            String accessToken = result.getString("access_token");
            Integer expiresIn = result.getInteger("expires_in") - 2;
            redisCacheTemplate.opsForValue().set(ToolRedisKey.DOU_YIN_ACCESS_TOKEN, accessToken, expiresIn, TimeUnit.SECONDS);
        }
        return "跳至授权成功页";
    }


    /**
     * 拼接获取授权的URL页面
     *
     * @return
     */
    @GetMapping("/getSilenceCode")
    public String getSilenceCode() {
        String scope = new StringBuilder()
                .append(ScopeEnum.USER_INFO.getCode())
                .toString();
        String redirectUri = "https://client.iotbox.cn/client/api/douyin/getSilenceCode/redirect";
        String state = "state_example";
        String url = douYinService.getSilenceCode(redirectUri, state);
        log.info("authUrl: " + url);
        return "redirect:" + url;
    }


    /**
     * 通过临时授权码获取用户accessToken
     *
     * @param request
     * @return
     */
    @GetMapping("/getSilenceCode/redirect")
    @ResponseBody
    public String getSilenceCodeRedirect(HttpServletRequest request) {

        Enumeration pNames = request.getParameterNames();
        while (pNames.hasMoreElements()) {
            String name = (String) pNames.nextElement();
            String value = request.getParameter(name);
            System.out.print(name + "=" + value);
        }
//
//        JSONObject result = douYinService.getAccessToken(code);
//        System.out.println(result);
//        String errorCode = result.getString("error_code");
//        if("0".equals(errorCode)){
//            String accessToken = result.getString("access_token");
//            Integer expiresIn = result.getInteger("expires_in")-2;
//            redisCache.setCacheObject(RedisKey.DOU_YIN_ACCESS_TOKEN,accessToken,expiresIn, TimeUnit.SECONDS);
//        }
        return "跳至授权成功页";
    }

    @PostMapping("/receive/webhooks")
    @ResponseBody
    public String receiveWebHooks(HttpServletRequest request) throws IOException {
        String header = request.getHeader("Msg-Id");
        System.out.println("header: " + header);


        String req = HuiLianHttpUtil.streamToString(request);
        JSONObject body = JSON.parseObject(req);
        System.out.println("body: " + body);
        String content = body.getString("content");

        String event = body.getString("event");
        if ("item_comment_reply".equals(event)) {
            System.out.println("用户评论视频");
        }


        return body.getString("content");
    }


}
